<?php
/**
 * Modelo CRUD de generico de uma tabela 1 para N
 * Lista trazendo o total de registros relacionados na tabela N
 * @example galeria trazendo o total de fotos
 * @author Emanuel Melo e Renato Lenz @ PC4 Team
 */
class PC4_Crud_Tabela1 extends PC4_Crud_Abstrato {
	
	public $tabelaN, $campoId, $fk, $ondeTabelaN, $total;

	public function __construct($tabela = 'galerias', $tabelaN = 'fotos', $total = '', $fk = '', $campoId = 'id', $ondeTabelaN = array(), $validacoes = array()) {
		parent::__construct($tabela, $validacoes);
		$this->tabelaN = $tabelaN;
		$this->campoId = $campoId;
		$this->total = (empty($total)) ? 'total' . ucfirst($this->tabelaN) : $total;
		$this->fk = (empty($fk)) ? $this->campoId . '_' . $this->tabela : $fk;
		$this->ondeTabelaN = '';
		foreach ($ondeTabelaN as $campo => $valor) {
			// TODO: Tentar achar uma expressao regular e trocar por esse strstr
			if (strstr($campo, '<') || strstr($campo, '>')) {
				$this->ondeTabelaN .= ' AND tbN.' . $campo . $valor;
			}
			else {
				$this->ondeTabelaN .= ' AND tbN.' . $campo . ' = ' . $valor;
			}
		}
	}

	public function lista($pagina = 1, $limite = 30, $debug = false) {
		$this->db->select(
			$this->letra . '.*,
			  (
			    SELECT
			      COUNT(*)
			    FROM
			      ' . $this->tabelaN . ' tbN
			    WHERE
			      tbN.' . $this->fk . ' = ' . $this->letra . '.' . $this->campoId . $this->ondeTabelaN . '
			  ) AS ' . $this->total, false
		);
		
		return parent::lista($pagina, $limite, $debug);

	}

}
?>